package khs.java_apache_httpclient_post.main.java;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException
    {
        String response = "";
        
        System.out.print("input url: ");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String input = bufferedReader.readLine();
        
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(input);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("param1", "value1"));
        urlParameters.add(new BasicNameValuePair("param2", "value2"));
        
        httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
        
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity entity = httpResponse.getEntity();
        
        StatusLine statusLine = httpResponse.getStatusLine();
        
        // 응답코드
        int statusCode = statusLine.getStatusCode();
        System.out.println(">>> statusCode: " + statusCode);
        
        if(entity != null){
            long contentLength = entity.getContentLength();
            BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
            
            String line = "";
            while((line = rd.readLine()) != null){
                response += line;
            }
        }
        
        httpResponse.close();
        httpPost.abort();
        System.out.println(response);
    }
}
